package com.jlnk.rxjavademo.view;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;

import androidx.appcompat.app.AppCompatActivity;

import com.jlnk.rxjavademo.adapter.ImageAdapter;
import com.jlnk.rxjavademo.R;
import com.jlnk.rxjavademo.entity.ImageEntity;
import com.jlnk.rxjavademo.presenter.MainPresenter;
import java.util.List;

public class MainActivity extends AppCompatActivity implements MainPresenter.MainView {
    private MainPresenter mainPresenter;
    private ListView listView;
    private ProgressBar progressBar;
    private ImageAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.listView);
        progressBar = findViewById(R.id.progressBar);

        mainPresenter = new MainPresenter(this);
        mainPresenter.loadImageData();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ImageEntity selectedImage = adapter.getItem(position);
                Intent intent = new Intent(MainActivity.this, ImageDetailActivity.class);
                intent.putExtra("imageUrl", selectedImage.getImageUrl());
                startActivity(intent);
            }
        });
    }

    @Override
    public void showLoading() {
        progressBar.setVisibility(ProgressBar.VISIBLE);
    }

    @Override
    public void hideLoading() {
        progressBar.setVisibility(ProgressBar.GONE);
    }

    @Override
    public void showError(String message) {
    }

    @Override
    public void updateList(List<ImageEntity> imageDataList) {
        if (adapter == null) {
            adapter = new ImageAdapter(this, imageDataList);
            listView.setAdapter(adapter);
        } else {
            adapter.updateData(imageDataList);
        }
    }
}